<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Easemob;
use App\Http\Controllers\SurveysController;
use App\Models\SmsLog;
use App\User;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use App\Util\Tool;

class RegisterController extends BaseController
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'string|max:255',
            'phone' => 'required|numeric|min:11', //new
            'code' => 'required|numeric',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $valid = $this->validator($request->all());
        if (count($valid->errors()) > 0) {
            return response()->json($valid->errors());
        }
        //获取手机号码
        $name = $request->name ?? Tool::generateUniqueUsername();
        $password = $request->password ?? '';
        $phone = $request->phone ?? '';
        $Pcode = $request->code ?? '';
        if (!Tool::checkMobile($phone)) {
            return $this->ResultJson(0, '请填写正确的手号码', []);
        }
        //检查用户是否存在
        if ($this->IssetUser($phone)) {
            return $this->ResultJson(0, '注册手机号已存在', []);
        }
        //判断用户是否发送短信验证请求
        if (empty($this->getCode($phone))) {
            return $this->ResultJson(0, '请发送短信验证码', []);
        }
        //需要检查验证码是否过期
        $code = Tool:: GetSmsvalidator($phone);
        if (empty($code)) {
            return $this->ResultJson(0, '验证码已经过期', []);
        }
        //检查验证码是否正确
        if ($Pcode != $code) {
            return $this->ResultJson(0, '验证码错误', []);
        }
        //更新验证码为验证过了
        $this->SetCode($phone, $code);
        //创建api_token
        $api_token = Tool::RandomToken($phone);
        //创建用户信息
        $data['name'] = $name;
        $data['phone'] = $phone;
        $data['password'] = bcrypt($password);
        $data['api_token'] = $api_token;
        $user = User::create($data);

        event(new Registered($user));

        //登录后写入redis api_token
        //环信聊天用户信息注册
        $tool = Tool::getUserNameForIm(['type' => 1, 'user_id' => $user->id]);
        (new Easemob())->createUser($tool['username'], $tool['password']);
        //注册问卷
        (new SurveysController())->register(['type' => 1, 'user_id' => $user->id]);
        Tool::SetAndUpToken($api_token, $phone);
        return $this->ResultJson(1, '注册成功', ['api_token' => $api_token]);
    }
}
